# coding=utf-8

from typing import Dict

from app.extensions import session_id_manager


class Variable:

    """
    VariablePool = {
        session_id: {
            project_id: {
                key: value,
                key1: value1,
                ...
            },
            project_id2: {
                ...
            }
        },
        session_id2:{
            ...
        }
    }
    """

    VariablePool = {}

    @classmethod
    def get_project_variable(cls, project_id):
        """
        获取项目中所有定义的变量
        :param id: 项目id
        :type id: int
        :return: 项目级所有变量
        :rtype: Dict
        """
        session_id = session_id_manager.get_session_id()
        cls._set_default_project_variable(project_id=project_id)
        return cls.VariablePool.get(session_id).get(project_id)

    @classmethod
    def set_project_variable(cls, project_id, key, value):
        """
        设置项目级别变量
        :param project_id: 项目id
        :type project_id: int
        :param key: 变量名
        :type key: str
        :param value: 变量值
        :type value: str
        """
        session_id = session_id_manager.get_session_id()
        cls._set_default_project_variable(project_id=project_id)
        cls.VariablePool.get(session_id).get(project_id).update({
            key: value
        })

    @classmethod
    def _set_default_project_variable(cls, project_id):
        """当VariablePool为空时，为其设置默认值，避免取出值为None的项目级变量池"""
        session_id = session_id_manager.get_session_id()
        session_var = cls.VariablePool.get(session_id)
        if session_var is None:
            cls.VariablePool.update({
                session_id: {
                    project_id: {}
                }
            })
            return
        project_var = cls.VariablePool.get(session_id).get(project_id)
        if project_var is None:
            cls.VariablePool.get(session_id).update({
                project_id: {}
            })
            return
